package com.rephilo.config;

import com.rephilo.pojo.Configuration;
import com.rephilo.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);

        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = new ArrayList<>();
        list.addAll(rootElement.selectNodes("//select"));
        list.addAll(rootElement.selectNodes("//insert"));
        list.addAll(rootElement.selectNodes("//update"));
        list.addAll(rootElement.selectNodes("//delete"));

        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultTye = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultTye);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlType(element.getName());
            String key = namespace + "." + mappedStatement.getId();
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
